package com.pingan.cashier.web;


import com.pingan.cashier.common.config.WeixinConfig;
import com.pingan.cashier.common.util.WechatSignUtil;
import com.pingan.cashier.service.impl.WexinNotifyProcess;
import com.pingan.cashier.web.resp.CommonResp;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @ClassName WechatNotifyController
 * @Description 微信支付结果回调处理
 * @Author chenrunquan126
 * @Date
 */
@RestController
@RequestMapping("/wechatpay")
@Slf4j
public class WechatNotifyController {

    private static Logger logger = LoggerFactory.getLogger(WechatNotifyController.class);

    @Resource
    private WexinNotifyProcess wexinNotifyProcess;

    @Resource
    private WeixinConfig weixinConfig;



    /**
     * 微信支付回调处理
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/result", method = RequestMethod.POST)
    public CommonResp appPayNotify(HttpServletRequest request) {
        CommonResp response = new CommonResp();
        try {
            String wechatNotifyStr = getRequestString(request);
            log.info("接收到【微信支付】结果回调请求，{0}", wechatNotifyStr);
            //验证签名
            boolean verifyResult = WechatSignUtil.verifySign(wechatNotifyStr, weixinConfig.getApiKey());
            if (!verifyResult) {
                throw new RuntimeException("验签失败");
            }
            //bizCode用于从库里查询时的参数,线上已有业务全为万里目,且会调到这个回调方法的都是已有数据,故这里全部配置为wanlimu_code
            response = wexinNotifyProcess.weixinPayNotify(wechatNotifyStr);
        } catch (Exception e) {
            log.error( "处理微信支付结果回调失败",e);
            response.setCode("FAIL");
        }

        return response;
    }




    private String getRequestString(HttpServletRequest request) throws IOException {
        //读取微信回调报文
        ServletInputStream instream = request.getInputStream();
        StringBuffer sb = new StringBuffer();
        int len = -1;
        byte[] buffer = new byte[1024];
        while ((len = instream.read(buffer)) != -1) {
            sb.append(new String(buffer, 0, len));
        }
        instream.close();
        //获得xml报文
        String wechatNotifyStr = sb.toString();
        return wechatNotifyStr;
    }


}
